package com.luom.fsp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.luom.fsp.annotation.AuthCheck;
import com.luom.fsp.common.BaseResponse;
import com.luom.fsp.common.DeleteRequest;
import com.luom.fsp.common.ErrorCode;
import com.luom.fsp.common.ResultUtils;
import com.luom.fsp.constant.UserConstant;
import com.luom.fsp.exception.BusinessException;
import com.luom.fsp.exception.ThrowUtils;
import com.luom.fsp.model.dto.carousel.CarouselAddRequest;
import com.luom.fsp.model.dto.carousel.CarouselQueryRequest;
import com.luom.fsp.model.dto.carousel.CarouselUpdateRequest;
import com.luom.fsp.model.entity.Carousel;
import com.luom.fsp.model.entity.User;
import com.luom.fsp.model.vo.CarouselVO;
import com.luom.fsp.service.CarouselService;
import com.luom.fsp.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 优惠券表接口
 *
*/
@RestController
@RequestMapping("/carousel")
@Slf4j
public class CarouselController {

    @Resource
    private CarouselService carouselService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建优惠券表
     *
     * @param carouselAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addCarousel(@RequestBody CarouselAddRequest carouselAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(carouselAddRequest == null, ErrorCode.PARAMS_ERROR);
        Carousel carousel = new Carousel();
        BeanUtils.copyProperties(carouselAddRequest, carousel);
        // 数据校验
        carouselService.validCarousel(carousel, true);
        // 写入数据库
        boolean result = carouselService.save(carousel);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newCarouselId = carousel.getId();
        return ResultUtils.success(newCarouselId);
    }

    /**
     * 删除优惠券表
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteCarousel(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        // 判断是否存在
        Carousel oldCarousel = carouselService.getById(id);
        ThrowUtils.throwIf(oldCarousel == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = carouselService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新优惠券表（仅管理员可用）
     *
     * @param carouselUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateCarousel(@RequestBody CarouselUpdateRequest carouselUpdateRequest) {
        if (carouselUpdateRequest == null || carouselUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Carousel carousel = new Carousel();
        BeanUtils.copyProperties(carouselUpdateRequest, carousel);
        // 数据校验
        carouselService.validCarousel(carousel, false);
        // 判断是否存在
        long id = carouselUpdateRequest.getId();
        Carousel oldCarousel = carouselService.getById(id);
        ThrowUtils.throwIf(oldCarousel == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = carouselService.updateById(carousel);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取优惠券表（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<CarouselVO> getCarouselVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Carousel carousel = carouselService.getById(id);
        ThrowUtils.throwIf(carousel == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(carouselService.getCarouselVO(carousel, request));
    }

    /**
     * 分页获取优惠券表列表（封装类）
     *
     * @param carouselQueryRequest
     * @return
     */
    @PostMapping("/list/page/vo")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Carousel>> listCarouselVOByPage(@RequestBody CarouselQueryRequest carouselQueryRequest) {
        long current = carouselQueryRequest.getCurrent();
        long size = carouselQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Carousel> carouselPage = carouselService.page(new Page<>(current, size),
                carouselService.getQueryWrapper(carouselQueryRequest));
        // 获取封装类
        return ResultUtils.success(carouselPage);
    }

    @GetMapping("/banners")
    public BaseResponse<List<CarouselVO>> getBanners() {
        QueryWrapper<Carousel> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("createTime");
        queryWrapper.eq("isUsed", 1);
        queryWrapper.last("limit 5");
        List<Carousel> carousels = carouselService.list();
        List<CarouselVO> carouselVOS = carousels.stream().map(carousel -> carouselService.getCarouselVO(carousel, null)).collect(Collectors.toList());
        return ResultUtils.success(carouselVOS);
    }


    // endregion
}
